/*
 * Wantmore - Service Delivery Platform.
 *
 * $Id: AlbumAddFormController.java 77 2010-11-12 14:54:43Z alexey.batyuta@gmail.com $
 *
 * Copyright 2010 by Sunbay Software Crimea Ltd.
 * All rights reserved
 */
package ua.crimea.bat.ss.forms;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import ua.crimea.bat.ss.model.beans.Album;
import ua.crimea.bat.ss.model.validators.AlbumValidator;
import ua.crimea.bat.ss.services.PhotoAlbumsService;

/**
 * User: bat
 * Date: Mar 26, 2010
 * Time: 8:57:25 AM
 */
@Controller("albumAddFormController")
@RequestMapping("/albums/new")
@SessionAttributes(types = Album.class)
public class AlbumAddFormController {
protected PhotoAlbumsService photoAlbumsService;

    public AlbumAddFormController() {
    }

    public void setPhotoAlbumsService(PhotoAlbumsService photoAlbumsService) {
        this.photoAlbumsService = photoAlbumsService;
    }

    public PhotoAlbumsService getPhotoAlbumsService() {
        return photoAlbumsService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }
    
    @Autowired
    public AlbumAddFormController(PhotoAlbumsService photoAlbumsService) {
        this.photoAlbumsService = photoAlbumsService;
    }

    @RequestMapping(method = RequestMethod.GET)
	public String setupForm(Model model) {
		Album album = new Album();
		model.addAttribute(album);
		return "albums/form";
	}

    @RequestMapping(method = RequestMethod.PUT)
	public String processSubmit(@ModelAttribute Album album, BindingResult result, SessionStatus status) {
		new AlbumValidator().validate(album, result);
		if (result.hasErrors()) {
			return "albums/form";
		}
		else {
			photoAlbumsService.storeAlbum(album);
			status.setComplete();
			return "redirect:/albums/" + album.getId();
		}
	}
    @RequestMapping(method = RequestMethod.POST)
	public String processSubmit2(@ModelAttribute Album album, BindingResult result, SessionStatus status) {
		new AlbumValidator().validate(album, result);
		if (result.hasErrors()) {
			return "albums/form";
		}
		else {
			photoAlbumsService.storeAlbum(album);
			status.setComplete();
			return "redirect:/albums/" + album.getId();
		}
	}
}
